package com.zzyl.nursing.service.impl;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.util.*;

import com.github.pagehelper.PageHelper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.AddFamilyDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.*;

import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.DataVo;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.nursing.vo.QueryFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 老人家属Service业务层处理
 * 
 * @author sumu
 * @date 2025-08-01
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper,FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private ElderFamilyMapper elderFamilyMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private TokenService tokenService;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of("山风沐雨",
            "薛定谔的猫",
            "鬼谷子的马",
            "流萤",
            "苏木",
            "哈吉米",
            "鼠鼠",
            "佘谨",
            "小欣欣"
    );

    //绑定家人
    @Override
    public void addFamily(AddFamilyDto dto) {
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, dto.getIdCard()));
        if (ObjectUtil.isEmpty(elder)){
            throw new BaseException("身份证信息错误");
        }
/*        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, elder.getId())
                .eq(Contract::getStatus,1));
        if (ObjectUtil.isEmpty(contract)){
            throw new BaseException("老人不存在");
        }*/
        Long userId = UserThreadLocal.getUserId();
        ElderFamily elderFamily = elderFamilyMapper.selectOne(Wrappers.<ElderFamily>lambdaQuery().eq(ElderFamily::getFamilyMemberId, userId)
                .eq(ElderFamily::getIdCard, dto.getIdCard()));
        if (ObjectUtil.isNotEmpty(elderFamily)){
            throw new BaseException("已经绑定过老人");
        }
        ElderFamily family = ElderFamily.builder().familyMemberId(userId)
                .elderId(elder.getId())
                .idCard(dto.getIdCard())
                .name(dto.getName())
                .remark(dto.getRemark())
                .build();
        elderFamilyMapper.insert(family);
    }

    //查询家人列表
    @Override
    public List<QueryFamilyVo> queryFamily() {
        List<ElderFamily> elderFamilies = elderFamilyMapper.selectList(null);
        ArrayList<QueryFamilyVo> vos = new ArrayList<>();
        for (ElderFamily elderFamily : elderFamilies) {
            QueryFamilyVo vo = new QueryFamilyVo();
            vo.setFamilyMemberId(elderFamily.getFamilyMemberId());
            vo.setId(elderFamily.getId());
            vo.setElderId(elderFamily.getElderId());
            vo.setElderName(elderFamily.getName());
            vos.add(vo);
        }
        return vos;
    }

    //分页查询
    @Override
    public List<ElderFamilyPage> queryFamilyPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        Long userId = UserThreadLocal.getUserId();
        List<ElderFamily> elderFamilies = elderFamilyMapper.selectList(Wrappers.<ElderFamily>lambdaQuery().eq(ElderFamily::getFamilyMemberId, userId));
        ArrayList<ElderFamilyPage> list = new ArrayList<>();
        for (ElderFamily elderFamily : elderFamilies) {
            Long elderId = elderFamily.getElderId();
            Elder elder = elderMapper.selectById(elderId);
            Bed bed = bedMapper.selectById(elder.getBedId());
            Room room = roomMapper.selectById(bed.getRoomId());
            Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getBindingLocation, elder.getId()));
            ElderFamilyPage elderFamilyPage = ElderFamilyPage.builder()
                    .elderId(elderId)
                    .mid(userId)
                    .bedNumber(elder.getBedNumber())
                    .image(elder.getImage())
                    .mremark(elderFamily.getRemark())
                    .name(elderFamily.getName())
                    .deviceName(device !=null ? device.getDeviceName() : null)
                    .iotId(device != null ? device.getIotId() : null)
                    .productKey(device != null ?device.getProductKey() : null)
                    .typeName(room.getTypeName())
                    .build();
            list.add(elderFamilyPage);
        }
        //直接返回列表，PageHelper会自动处理分页
        return list;
    }

    @Override
    public List<DataVo> queryDeviceDataListByDay(String iotId, String functionId, Long startTime, Long endTime) {
        LocalDateTime startT = LocalDateTimeUtil.of(startTime);
        LocalDateTime endT = LocalDateTimeUtil.of(endTime);
        LocalDateTime begin=startT;
        LocalDateTime end=begin.plusHours(1L);
        List<DataVo> list=new ArrayList<>();
        while(begin.isBefore(endT)){
            DeviceData deviceData = deviceDataMapper.selectOne(Wrappers.<DeviceData>lambdaQuery()
                    .eq(DeviceData::getIotId, iotId)
                    .eq(DeviceData::getFunctionId, functionId)
                    .between(DeviceData::getAlarmTime, begin, end)
                    .orderByAsc(DeviceData::getAlarmTime)
                    .orderByAsc(DeviceData::getAlarmTime)
                    .last("limit 1"));
            DataVo vo=new DataVo();
            vo.setDateTime(begin);
            if(ObjectUtil.isNotEmpty(deviceData)){
                vo.setDataValue(Double.parseDouble(deviceData.getDataValue()));
            }else{
                vo.setDataValue(0d);
            }
            list.add(vo);
            begin=begin.plusHours(1L);
            end=end.plusHours(1L);
        }
        return list;

    }


    @Override
    public List<DataVo> queryDeviceDataListByWeek(String iotId, String functionId, Long startTime, Long endTime) {
        LocalDateTime startT = LocalDateTimeUtil.of(startTime);
        LocalDateTime endT = LocalDateTimeUtil.of(endTime);
        /*List<DeviceData> deviceDataList = deviceDataMapper.selectList(Wrappers.<DeviceData>lambdaQuery()
                .eq(DeviceData::getIotId, iotId)
                .eq(DeviceData::getFunctionId, functionId)
                .between(DeviceData::getAlarmTime, startT, endT)
                .orderByAsc(DeviceData::getAlarmTime));*/
        LocalDateTime begin=startT;
        LocalDateTime end=begin.plusDays(1L);
        List<DataVo> list=new ArrayList<>();
        while(begin.isBefore(endT)){
            boolean flag=false;
            List<DeviceData> deviceDataList = deviceDataMapper.selectList(Wrappers.<DeviceData>lambdaQuery()
                    .eq(DeviceData::getIotId, iotId)
                    .eq(DeviceData::getFunctionId, functionId)
                    .between(DeviceData::getAlarmTime, begin, end)
                    .orderByAsc(DeviceData::getAlarmTime));
            DataVo vo=new DataVo();
            Double sum=0d;
            int size=0;
            LocalDateTime alarmTime=null;
            for (DeviceData deviceData : deviceDataList) {
                alarmTime = deviceData.getAlarmTime();
                if(!flag &&alarmTime.isBefore(end)&&alarmTime.isAfter(begin)){
                    sum=sum+Double.parseDouble(deviceData.getDataValue());
                    size++;
                    flag=true;
                }
            }
            vo.setDateTime(alarmTime);
            Double avg=sum/size;
            vo.setDataValue(avg);
            list.add(vo);
            begin=begin.plusDays(1L);
            end=end.plusDays(1L);
        }
        return list;
    }

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return familyMemberMapper.selectById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }


    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        familyMember.setCreateTime(DateUtils.getNowDate());
        return familyMemberMapper.insert(familyMember);
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        familyMember.setUpdateTime(DateUtils.getNowDate());
        return familyMemberMapper.updateById(familyMember);
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return familyMemberMapper.deleteByIds(Arrays.asList(ids));
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return familyMemberMapper.deleteById(id);
    }

    /**
     * 登录
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {
        //获取openid
        String openId = wechatService.getOpenid(dto.getCode());
        //获取手机号
        String phone = wechatService.getPhone(dto.getPhoneCode());
        //和数据库保持同步
        FamilyMember familyMember = familyMemberMapper.selectOne(Wrappers.<FamilyMember>lambdaQuery()
                .eq(FamilyMember::getOpenId, openId));
        if(ObjectUtil.isEmpty(familyMember)){
            familyMember=familyMember.builder()
                    .openId(openId)
                    .build();
        }
        familyMember.setPhone(phone);
        if(ObjectUtil.isEmpty(familyMember.getId())){
            //新增
            int index = RandomUtil.randomInt(DEFAULT_NICKNAME_PREFIX.size());
            familyMember.setName(DEFAULT_NICKNAME_PREFIX.get(index));
            familyMemberMapper.insert(familyMember);
        }else{
            //修改
            familyMemberMapper.updateById(familyMember);
        }
        //生成令牌
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId",familyMember.getId());
        claims.put("userName",familyMember.getName());
        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());
        return loginVo;
    }


    }



